import {
  Inject,
  Injectable,
  Logger,
  HttpException,
  HttpStatus,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { RedisService } from 'src/redis/redis.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { LoginUserDto } from './dto/login-user.dto';
import { UpdateUserPasswordDto } from './dto/updateUserPasswordDto';
import { md5 } from 'src/utils';
import { EmailService } from 'src/email/email.service';
import { JwtService } from '@nestjs/jwt';
import { UpdateUserDto } from './dto/update-user.dto';

@Injectable()
export class UserService {
  @Inject(EmailService)
  private readonly emailService: EmailService;

  @Inject(PrismaService)
  private readonly prismaService: PrismaService;

  @Inject(RedisService)
  private readonly redisService: RedisService;

  @Inject(JwtService)
  private readonly jwtService: JwtService;

  private logger = new Logger();

  // 发送邮箱验证码
  async sendCaptcha(email: string) {
    if (!email) {
      throw new BadRequestException('邮箱地址不能为空');
    }
    const code = Math.random().toString().substr(2, 6);

    // 将验证码存入redis，并设置过期时间为5分钟
    await this.redisService.set(`captcha_${email}`, code, 60 * 5);

    // 发送邮件
    await this.emailService.sendMail({
      to: email,
      subject: '注册验证码',
      html: `您的注册验证码为：${code}，有效期为 5 分钟，请尽快完成注册。`,
    });

    return '发送成功';
  }

  // 发送修改密码邮箱验证码
  async sendUpdatePasswordCaptcha(email: string) {
    if (!email) {
      throw new BadRequestException('邮箱地址不能为空');
    }
    const code = Math.random().toString().substr(2, 6);

    // 将验证码存入redis，并设置过期时间为5分钟
    await this.redisService.set(`captcha_${email}`, code, 60 * 5);

    // 发送邮件
    await this.emailService.sendMail({
      to: email,
      subject: '更改密码验证码',
      html: `您的更改密码验证码为：${code}，有效期为 5 分钟，请尽快完成修改。`,
    });

    return '发送成功';
  }

  // 注册用户
  async register(user: RegisterUserDto) {
    // const captcha = await this.redisService.get(`captcha_${user.email}`);
    // if (!captcha) {
    //   throw new HttpException('验证码已失效', HttpStatus.BAD_REQUEST);
    // }
    // if (captcha !== user.captcha) {
    //   throw new HttpException('验证码不正确', HttpStatus.BAD_REQUEST);
    // }

    const isUserExist = await this.prismaService.user.findUnique({
      where: {
        username: user.username,
      },
    });

    if (isUserExist) {
      throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST);
    }

    try {
      return this.prismaService.user.create({
        data: {
          username: user.username,
          password: md5(user.password),
          email: user.email,
          nickName: user.nickName,
        },
        select: {
          id: true,
          username: true,
          email: true,
          nickName: true,
          avatar: true,
          createTime: true,
        },
      });
    } catch (error) {
      this.logger.error(error, UserService);
      return null;
    }
  }

  // 用户登录
  async login(userDto: LoginUserDto) {
    const user = await this.prismaService.user.findUnique({
      where: {
        username: userDto.username,
      },
    });

    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }

    if (user.password !== md5(userDto.password)) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST);
    }

    delete user.password;

    return {
      user,
      token:
        'Bearer ' +
        this.jwtService.sign(
          {
            userId: user.id,
            username: user.username,
          },
          {
            expiresIn: '7d',
          },
        ),
    };
  }

  // 获取用户信息
  async getUserInfoById(userId: number) {
    return await this.prismaService.user.findUnique({
      where: {
        id: userId,
      },
      select: {
        id: true,
        username: true,
        nickName: true,
        email: true,
        avatar: true,
        sex: true,
        createTime: true,
      },
    });
  }

  // 修改密码
  async updateUserPassword(passwordDto: UpdateUserPasswordDto) {
    // 1. 邮箱验证码是否正确
    const captcha = await this.redisService.get(`captcha_${passwordDto.email}`);
    if (!captcha) {
      throw new HttpException('验证码已失效', HttpStatus.BAD_REQUEST);
    }
    if (captcha !== passwordDto.captcha) {
      throw new HttpException('验证码不正确', HttpStatus.BAD_REQUEST);
    }
    // 2. 用户是否存在
    const user = await this.prismaService.user.findUnique({
      where: {
        username: passwordDto.username,
      },
    });

    console.log('用户更新密码', user);

    // 3. 最后修改密码
    user.password = md5(passwordDto.password);
    try {
      await this.prismaService.user.update({
        where: {
          id: user.id,
        },
        data: user,
      });
      return '密码修改成功';
    } catch (err) {
      this.logger.error(err, UserService);
      return '密码修改失败';
    }
  }

  // 修改用户信息
  async update(userId: number, updateUserDto: UpdateUserDto) {
    const user = await this.prismaService.user.findUnique({
      where: {
        id: userId,
      },
    });

    if (updateUserDto.nickName) {
      user.nickName = updateUserDto.nickName;
    }
    if (updateUserDto.avatar) {
      user.avatar = updateUserDto.avatar;
    }

    try {
      await this.prismaService.user.update({
        where: {
          id: userId,
        },
        data: user,
      });
      return '用户信息修改成功';
    } catch (err) {
      this.logger.error(err, UserService);
      return '用户信息修改失败';
    }
  }

  // 退出登录
  async logout(){
  }
}
